<template>
  <div class="app-container">
    <el-form ref="queryFormRef" :inline="true" size="small" :model="queryParams" class="demo-form-inline"
             v-hasPermi="['res:query:query']">
      <el-form-item label="网站名称" prop="name">
        <el-input v-model.trim="queryParams.name" :maxlength="50" placeholder="请输入名称"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="searchHandler">查询</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" @click="resetHandler">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20">
      <el-col :span="24">
        <div class="grid-content bg-purple">
          <el-button plain type="primary" size="mini" icon="el-icon-plus" v-hasPermi="['res:query:add']"
                     @click="openDialog(null)">增加
          </el-button>
<!--          <el-button plain type="warning" size="mini" icon="el-icon-download" v-hasPermi="['res:query:export']"-->
<!--                     @click="exportHandler">导出-->
<!--          </el-button>-->
        </div>
      </el-col>
    </el-row>

    <el-table
      ref="tableRef"
      :data="tableData"
      highlight-current-row
      max-height="600"
      v-loading="loading"
      v-horizontal-scroll="'auto'"
      @row-click="rowClick"
      style="width: 100%;margin-top: 10px;">
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column
        property="name"
        label="网站名称"
        align="center"
      />
      <el-table-column
        property="address"
        label="网址"
        align="center"
      />
      <el-table-column
        property="remark"
        label="备注"
        align="center"
      />
      <el-table-column
        property="createBy"
        label="创建人"
        align="center"
      />
      <el-table-column
        property="createTime"
        label="创建时间"
        align="center"
        min-width="140"
        sortable
      />
      <el-table-column
        label="操作"
        align="center"
        v-if="$auth.hasPermi('res:query:edit') || $auth.hasPermi('res:query:remove')"
      >
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" v-hasPermi="['res:query:edit']" @click="openDialog(scope.row)">
            修改
          </el-button>
          <el-popconfirm
            confirm-button-text="是"
            cancel-button-text="否"
            title="确定删除吗？"
            @confirm="deleteHandler(scope.row)"
          >
            <el-button slot="reference" icon="el-icon-delete" v-hasPermi="['res:query:remove']" type="text"
                       style="margin-left: 10px">删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <div style="margin-top: 10px;" v-if="$auth.hasPermi('res:query:account:list')">
      <el-tabs v-model="activeName">
        <el-tab-pane label="账号信息" name="1">
          <CompanyAccount :siteInfo="siteInfo" v-if="siteInfo.id"/>
        </el-tab-pane>
      </el-tabs>
    </div>

    <el-dialog
      :title="dialogTitle === 1 ? '新增' : '修改'"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :fullscreen="device === 'mobile'"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px" class="demo-form"
               :label-position="device === 'mobile' ? 'top' : 'right'">
        <el-form-item label="网站名称" prop="name">
          <el-input v-model.trim="form.name" placeholder="请输入网站名称" :maxlength="30"/>
        </el-form-item>
        <el-form-item label="网址" prop="address">
          <el-input v-model.trim="form.address" placeholder="请输入网址" :maxlength="50"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" :autosize="{ minRows: 2, maxRows: 6 }" type="textarea" :maxlength="200"
                    placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="uploadLoading" @click="submitForm('formRef')">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addDataApi, deleteDataApi, getDataListApi, updateDataApi} from "@/api/saas/research/project/query";
import {getUserProfile} from "@/api/system/user";
import {uploadImgApi} from "@/api/after/serve";
import {mapGetters} from 'vuex'
import CompanyAccount from "./components/account.vue";

export default {
  name: 'ResearchQuery',
  components: { CompanyAccount },
  dicts: [],
  data() {
    return {
      activeName: "1",
      uploadLoading: false, // 上传动画
      env: process.env.VUE_APP_STATIC_API || "",
      // 加载动画
      loading: true,
      // 省份数据
      provinceList: [],
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 新增和修改参数
      form: {
        address: "",
        name: "",
        createBy: "", // 创建人 *
        createTime: "", // 创建时间 *
        id: null, // id
        remark: "", // 备注
        updateBy: "", // 更新时间
        updateTime: "", // 更新人
      },
      // 表单的校验规则
      rules: {
        address : [
          {required: true, message: '请填写网址', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请填写网站名称', trigger: 'blur'}
        ],
      },
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        address: "",
        name: "",
        pageNum: 1,
        pageSize: 10,
      },
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
      // 博诺集团数据
      companyList: [],
      // 网站信息
      siteInfo: {
        id: null
      },
    }
  },
  computed: {
    ...mapGetters([
      'device'
    ]),
  },
  created() {
    this.getList()
    this.getUserinfo()
  },
  activated() {
    this.getList()
  },
  methods: {
    // 点击表格行
    rowClick(row) {
      this.siteInfo = { ...row }
    },
    // 查看合同
    handleView(url) {
      window.open(this.env + url)
    },
    // 上传全部图片
    async uploadImg(fileList = [], cb = () => {
    }) {
      if (fileList.length <= 0) {
        cb && cb("")
        return false
      }

      const urlList = (fileList ?? []).filter(i => !i.raw).map(i => i.url)

      if (urlList && urlList[0]) return false

      if (fileList.length <= 0) {
        this.form.certification = ""
        return false
      }

      const file = fileList[0]
      const formData = new FormData()
      formData.append('file', file.raw)
      const {fileName} = await uploadImgApi(formData)

      cb && cb(fileName)
    },
    // 获取根据list中的value返回label
    getListValue(data, list, value = 'value') {
      let label = ''
      list.map((item) => {
        if (+item[value] === +data) {
          label = item.label
        }
      })
      return label
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 获取数据
    async getList() {
      this.loading = true
      const res = await getDataListApi(this.queryParams)
      if (res.code === 200) {
        this.tableData = res.rows
        this.total = res.total
      }
      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {
        this.form = {
          ...row,
        }
        this.dialogTitle = 2
      } else {
        this.form = {...this.$options.data().form}
        this.dialogTitle = 1
      }
      this.dialogVisible = true
      this.resetForm('formRef')
    },
    // 导出的回调
    async exportHandler() {
      this.download('saas/researchProjectQuery/export', {
        ...this.queryParams,
        userId: this.user.userId,
        deptId: this.user.deptId,
      }, `researchProjectQuery_${new Date().getTime()}.xlsx`)
    },
    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.dialogTitle === 1) {
            this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
        userId: this.user.userId,
      }
      const res = await addDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        updateBy: this.user.nickName,
      }
      const res = await updateDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },
    // 重置的回调
    resetHandler() {
      this.resetForm('queryFormRef')
    },
  },
}
</script>

<style scoped lang="scss">

</style>
